package com.liuyucheng.idea_springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liuyucheng.annotation.NotAllowRepeat;
import com.liuyucheng.idea_springboot.bean.Lyc;
import com.liuyucheng.idea_springboot.bean.LycUser;
import com.liuyucheng.idea_springboot.bean.Result;
import com.liuyucheng.idea_springboot.exception.BaseException;
import com.liuyucheng.idea_springboot.mybatisplus.generator.entity.TYwhcPgforecastn;
import com.liuyucheng.idea_springboot.mybatisplus.generator.mapper.TYwhcPgforecastnMapper;
import com.liuyucheng.idea_springboot.service.LycUserService;
import com.liuyucheng.idea_springboot.util.IpUtil;
import com.liuyucheng.idea_springboot.util.ResultUtil;
import com.liuyucheng.idea_springboot.wechat.mini.service.WeChatMiniService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {

    @Resource
    private TYwhcPgforecastnMapper tYwhcPgforecastnMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private WeChatMiniService weChatMiniService;
    @Resource
    private LycUserService lycUserService;

    @Value("${environment.profile}")
    private String environment;

    @Transactional(noRollbackFor = StringIndexOutOfBoundsException.class)
    @GetMapping("/testTransaction")
    public Result<Object> testTransaction(HttpServletRequest request) {
        LycUser user = new LycUser();
        user.setUsername("测试人");
        user.setNickname("测试人");
        user.setStatus(1);
        user.setPassword("xxx");
        lycUserService.save(user);

        String str = "";
        char c = str.charAt(3);

        return Result.ok("成功");
    }

    @GetMapping("/testProfile")
    public Result<Object> testProfile(HttpServletRequest request) throws Exception {
        log.info("当前的环境为：{}", environment);

        try {
            char c = "".charAt(2);
        } catch (Exception e) {
            log.info("处理失败");
            e.printStackTrace();
        }

        return Result.ok(environment);
    }

    @PostMapping("/testRedisLock")
    public Result<Object> testRedisLock(HttpServletRequest request) {
        Boolean result = null;
        try {
            result = redisTemplate.opsForValue().setIfAbsent("lock", "ImValue", 60, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("设置分布式锁失败！");
        }
        if (Boolean.TRUE.equals(result)) {
            return Result.data("加锁成功");
        }
        return Result.data("加锁失败");
    }

    /**
     * 获取下拉框信息
     */
    @SneakyThrows
    @PostMapping("/testGetMac")
    public Result<Object> testGetMac(HttpServletRequest request) {
        String ipAddr = IpUtil.getIpAddr(request);
        System.out.println("ipAddr = " + ipAddr);
        return Result.data(ipAddr);
    }

    /**
     *
     */
    @PostMapping("/testExHandler")
    public Result<Object> testExHandler(HttpServletRequest request) throws Exception {
        String text = "";
        extracted(text);
        return Result.data(new Object());
    }

    @SneakyThrows
    private static void extracted(String text) {
        if (!text.equals("ddd")) {
            throw new BaseException("出异常了");
        }
    }

    /**
     *
     */
    @PostMapping("/testMP")
    public Result<Object> testMP(HttpServletRequest request) {
        List<TYwhcPgforecastn> list = tYwhcPgforecastnMapper.selectList(
                new QueryWrapper<TYwhcPgforecastn>()
//                        .eq("GUID", 1)
//                        .isNotNull("RECEIVE_STATUS")
        );
        return Result.data(list);
    }

    /**
     * 测试如何定位JVM问题
     */
    List<Lyc> list = new ArrayList<>();

    @PostMapping("/testJVM")
    public Result<Object> testJVM(HttpServletRequest request) {
        new Thread(() -> {
            for (int i = 0; i < 1000000; i++) {
                Lyc lyc = new Lyc().setName("ddddd");
                list.add(lyc);
            }
        }).start();
        return Result.ok();
    }

    /**
     * 测试重复提交切面
     *
     * @param request 请求
     * @param params  参数
     */
    @NotAllowRepeat(type = NotAllowRepeat.SUBMIT)
    @PostMapping("/testAspect")
    public void testAspect(HttpServletRequest request, @RequestBody Map<String, String> params) {
        log.info("方法正常执行");
    }

    /**
     * 获取openId
     *
     * @param paraMap
     * @return
     */
    @PostMapping(value = "/getOpenId")
    public ResultUtil<?> getOpenId(@RequestBody Map<String, String> paraMap) {
        String code = paraMap.get("code");
        String openId = weChatMiniService.getOpenId(code);
        return ResultUtil.success(openId);
    }

    public static void bubbleSort(int[] array) {
        if (array == null || array.length == 0) {
            return;
        }

        int n = array.length;
        boolean swapped;
        for (int i = 0; i < n - 1; i++) {
            swapped = false;
            for (int j = 0; j < n - 1 - i; j++) {
                if (array[j] > array[j + 1]) {
                    // 交换两个元素
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                    swapped = true;
                }
            }
            // 如果在这一趟排序中没有发生交换，则说明数组已经排序好，可以提前退出
            if (!swapped) {
                break;
            }
        }
    }

    // 测试冒泡排序的正确性
    public static void main(String[] args) {
        Map<Integer, String> statusMap = new HashMap<Integer, String>();
        String res = statusMap.getOrDefault(4, "未知状态");
        System.out.println("res = " + res);
    }

}
